/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.coverage_measuring.mutator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

class SortableHashSet<T> extends HashSet<T> implements SortableSet<T> {
	public SortableHashSet() {
		super();
	}

	public SortableHashSet(Collection<? extends T> collection) {
		super(collection);
	}

	public SortableHashSet(int initialCapacity, float loadFactor) {
		super(initialCapacity, loadFactor);
	}

	public SortableHashSet(int initialCapacity) {
		super(initialCapacity);
	}

	public List<T> sort(Comparator<T> comparator) {
		List<T> list = new ArrayList<T>(this);

		Collections.sort(list, comparator);

		return list; 
	}

	public List<T> sort() {
		List<T> list = new ArrayList<T>(this);

		try {
			Collections.sort(convertToComparable(list));

			return list; 
		}
		catch (ClassCastException classCastException) {
			throw new UnsupportedOperationException(
				"You cannot sort this set as its elements are not comparable");
		}
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation methods
	///////////////////////////////////////////////////////////////////////////////////////////////
	
	@SuppressWarnings("unchecked")
	private static <T, E extends Comparable<? super E>> List<E> convertToComparable(List<T> list) {
		return (List<E>) list;
	}
}